import React, { useEffect, useState } from 'react';
import { connect } from 'react-redux';
import { render } from 'react-dom';
import { Tooltip } from 'antd';
import { data as heatmapData } from './data'
import { SHUI_ZHAN } from '../constants/water';
import './gis.less'
const MAPDOMID = 'fs-amap-container1';
let map = null;
let heatmap = null;
let loca = null;
let gridLayer = null;

function Map(props) {
    const { trendData, waterLevelAlarms, emergencyList, getPumpStatusData } = props;
    const [delay, setDelay] = useState(true)
    const [tab, setTab] = useState('overview')

    // 地图初始化
    const loadMap = () => {
        // 图片图层 实现瓦片地图中国地图样式 bounds 第一个点为左下角 第二个点为右上角
        const imageLayer = new AMap.ImageLayer({
            url: '/assets/images/map1.svg',
            bounds: new AMap.Bounds(
                [115.800221, 28.225659],
                [116.334849, 28.973298],
            ),
            zooms: [3, 14],
        });

        map = new AMap.Map(MAPDOMID, {
            center: [116.061261, 28.509558],
            zoomEnable: true,
            dragEnable: true,
            viewMode: '3D',
            pitch: 48.10000000000003,
            labelzIndex: 130,
            zoom: 10.75,
            rotation: 12.299999999999997,
            cursor: 'pointer',
            mapStyle: 'amap://styles/300b147a96946a4f1c1b1b8eb1f92f76',
            layers: [
                AMap.createDefaultLayer(),
                imageLayer,
            ],
        });

        map.on('complete', () => {
            setDelay(false)
            map && renderMarkers()
            map && renderAlarms()
            setTimeout(() => {
                renderLayer()
                createText()
            }, 1000);
        });

        map.on('click', (e) => {
            if (!e && !e.lnglat) {
                return
            }

            const zoom = map.getZoom();
            const pitch = map.getPitch();
            const center = map.getCenter();
            const Rotation = map.getRotation();
            console.log('zoom' + zoom)
            console.log('pitch' + pitch)
            console.log('center' + center)
            console.log('Rotation' + Rotation)
            console.log('e.lnglat' + e.lnglat)
        })

        loca = new Loca.Container({ map: map })
        // { map && renderMarkers() }
        // { map && renderAlarms() }
        // setTimeout(() => {
        //     renderLayer()
        //     createText()
        // }, 1000);
    };

    // 初始化GIS 组件销毁清空定时器
    useEffect(() => {
        if (!map) loadMap();
        return () => {
            map = null;
            heatmap = null;
            loca = null;
            gridLayer = null;
        }
    }, []);

    useEffect(() => {
        if (map) {
            setTimeout(() => {
                renderLayer()
                createText()
                renderAlarms()
            }, 500);

        }

    }, [trendData, waterLevelAlarms]);


    const renderMarkers = () => {
        map.clearMap();
        // map.setZoom(10.3)
        // map.setCenter([116.054664, 28.538966])
        // map.setPitch(48.10000000000003)
        // map.setRotation(1.7000)
        if (loca && heatmap) loca.remove(heatmap)

        //初始层级 zoom14以下显示聚合点
        // const data = [
        //     { lng: 116.117906, lat: 28.678096, type: 'home', name: '泵站1', kind: 'markergreen' },
        //     { lng: 116.195238, lat: 28.842114, type: 'home', name: '泵站2', kind: 'markerblue' },
        //     { lng: 116.037227, lat: 28.558811, type: 'home', name: '泵站3', kind: 'markeryellow' },
        //     { lng: 115.925856, lat: 28.558811, type: 'home', name: '泵站4', kind: 'markergreen' },
        //     { lng: 115.989847, lat: 28.484411, type: 'home', name: '泵站5', kind: 'markergreen' },
        // ]

        //初始点位显示
        SHUI_ZHAN.map((x, index) => {
            var marker = new AMap.Marker({
                position: new AMap.LngLat(x.location[0], x.location[1]),
                // 将一张图片的地址设置为 icon
                icon: '/assets/images/homepage/water/_monitor.png',
                // 设置了 icon 以后，设置 icon 的偏移量，以 icon 的 [center bottom] 为原点
                offset: new AMap.Pixel(-13, -30),
                zooms: [3, 14],
            });
            marker.setTitle(x.name);
            map.add(marker);
            let infowindow = new AMap.InfoWindow({
                isCustom: true,  //使用自定义窗体
                content: `<div id="map-content" class="water-gis-infowindow">
        <div style="height:${360}px;" id="contentid${x.name}"></div></div>`,
                offset: new AMap.Pixel(153, 260)
            });

            marker.on('click', async () => {
                let position = marker.getPosition ? marker.getPosition() : marker.getCenter();
                infowindow.open(map, position);
                map.setCenter(position);
                let pumpStatus = [];
                if (x.structId) {
                    const res = await getPumpStatusData(x.structId);
                    if (res?.payload?.data?.stations) {
                        pumpStatus = res.payload.data.stations;
                    }
                }
                setTimeout(() => {
                    if (document.getElementById(`contentid${x.name}`)) {
                        render(<div>
                            <div className='gis_exit'
                                style={{ right: 6, top: 67 }}
                                onClick={() => {
                                    map.setCenter([115.922069, 28.554867])
                                    map.clearInfoWindow();
                                }} />
                            <div className='gis_item'>
                                <span className='gis_title'>泵站名称：</span>
                                <span className='gis_text'>{x.name}</span>
                            </div>
                            <div className='gis_item_box'>
                                {
                                    pumpStatus?.map(s => <div className='gis_item' key={s.id}>
                                        <span className='gis_title'>{s.name}：</span>
                                        <div className={[2, 4, 6].includes(s.data[0]?.sMotor_State) ? 'gis_text_on' : 'gis_text_off'}>
                                        </div>
                                    </div>)
                                }
                            </div>
                        </div>,
                            document.getElementById(`contentid${x.name}`));
                    }
                }, 50)
            })
        })


        if (tab == 'device') {
            const data = [
                { lng: 115.921895, lat: 28.556351, type: 'device', name: '廉租房1', kind: 'devicemarker' },
                { lng: 115.920839, lat: 28.555323, type: 'device', name: '廉租房2', kind: 'devicemarker' },
                { lng: 115.918329, lat: 28.55445, type: 'device', name: '廉租房3', kind: 'devicemarker' },
                { lng: 115.919309, lat: 28.553166, type: 'device', name: '廉租房1', kind: 'devicemarker' },
                { lng: 115.921585, lat: 28.553925, type: 'device', name: '廉租房2', kind: 'devicemarker' },
                { lng: 115.92565, lat: 28.556996, type: 'device', name: '廉租房3', kind: 'devicemarker' },
                { lng: 115.922671, lat: 28.558769, type: 'device', name: '廉租房1', kind: 'devicemarker' },
            ]

            data.filter(s => s.type == tab).map((x, index) => {
                var marker = new AMap.Marker({
                    position: new AMap.LngLat(x.lng, x.lat),
                    // 将一张图片的地址设置为 icon
                    icon: '/assets/images/homepage/communtity/' + x.kind + '.png',
                    // 设置了 icon 以后，设置 icon 的偏移量，以 icon 的 [center bottom] 为原点
                    offset: new AMap.Pixel(-13, -30),
                    zooms: [15, 19],
                });
                marker.setTitle(x.name);
                map.add(marker);
            })
        }


    }

    const renderAlarms = () => {
        if (tab == 'person' || !waterLevelAlarms.length || !trendData.length) {
            return;
        }
        const alarms = waterLevelAlarms.map(a => {
            let alarm = {
                lng: a.lng,
                lat: a.lat,
                // type: 'device', 
                name: a.alarms[0]?.source.name,
                kind: 'markeralarm'
            };
            for (const t of trendData) {
                if (t?.id == a.alarms[0]?.source.id) {
                    alarm.waterLevel = t.waterLevel;
                    alarm.alert = t.alert;
                }
            }
            return alarm;
        })
        alarms.map((x, index) => {
            var marker = new AMap.Marker({
                position: new AMap.LngLat(x.lng, x.lat),
                // 将一张图片的地址设置为 icon
                icon: '/assets/images/homepage/communtity/' + x.kind + '.png',
                // 设置了 icon 以后，设置 icon 的偏移量，以 icon 的 [center bottom] 为原点
                offset: new AMap.Pixel(-13, -30),
                zooms: [3, 14],
                zIndex: 13,
            });
            marker.setTitle(x.name);
            map.add(marker);

            let infowindow = new AMap.InfoWindow({
                isCustom: true,  //使用自定义窗体
                content: `<div id="map-content" class="gis-infowindow-alarm">
                    <div style="height:${360}px;" id="alarmcontentid${x.name}"></div></div>`,
                offset: new AMap.Pixel(233, 260)
            });

            let alarmOk = new AMap.InfoWindow({
                isCustom: true,  //使用自定义窗体
                // content: `<div id="map-content" class="gis-infowindow gis-infowindow-alarm">
                //     <div style="height:${360}px;" id="contentid${x.name}"></div></div>`,
                offset: new AMap.Pixel(233, 440)
            });

            marker.on('click', () => {
                let position = marker.getPosition ? marker.getPosition() : marker.getCenter();
                infowindow.open(map, position);
                // map.setCenter(position)
                setTimeout(() => {
                    if (document.getElementById(`alarmcontentid${x.name}`)) {
                        render(<div>
                            <div className='gis_exit' onClick={() => {
                                map.setCenter([115.922069, 28.554867])
                                map.clearInfoWindow();
                            }} />
                            <div className='gis_item'>
                                <span className='gis_title'>点位名称</span>
                                <span className='gis_text'>{x.name}</span>
                            </div>
                            <div className='gis_item'>
                                <span className='gis_title'>实时水位</span>
                                <span className='gis_text'>{x.waterLevel}m</span>
                            </div>
                            <div className='gis_item'>
                                <span className='gis_title'>预警水位</span>
                                <span className='gis_text'>{x.alert}m</span>
                            </div>
                            <div className='gis_item'>
                                <span className='gis_title'>近1h雨量</span>
                                <span className='gis_text'>1.5mm</span>
                            </div>
                            <div className='gis_item'>
                                <span className='gis_title'>告警</span>
                                <span className='gis_text'>高风险</span>
                            </div>

                        </div>,
                            document.getElementById(`alarmcontentid${x.name}`));
                    }
                }, 50)
            })
        })
    }

    const renderLeftTop = () => {
        let hCount = 0, mCount = 0, lCount = 0;
        for (const a of waterLevelAlarms) {
            switch (a.alarms[0].level) {
                case 1:
                    hCount += 1
                    break;
                case 2:
                    mCount += 1
                    break;
                case 3:
                    lCount += 1
                    break;
                default:
                    break;
            }
        }
        return <div className='water_gis_home_left'>
            {[{ name: '高风险区域', key: 'high', data: hCount },
            { name: '中风险区域', key: 'middle', data: mCount },
            { name: '低风险区域', key: 'low', data: lCount }].map(s => {
                return <div className='left_item'>
                    <div className='gis_item_left'>
                        <div className={`${s.key}_risk`} />
                    </div>
                    <div className='gis_item_right'>
                        <div>{s.name}</div>
                        <div><span className={`${s.key}_text`}>{s.data}</span>/{trendData.length}</div>
                    </div>
                </div>
            })}
        </div>
    }

    const renderRightBottom = () => {
        return tab == 'overview' ?
            <div className='water_home_right'>
                <div className='_right_row1'>
                    <div className='_monitor' /><span className='monitor_text'>监测点</span></div>
                <div className='_right_row2'>
                    <span className='column1'>预警阈值参照表</span>
                    <div className='column2'>
                        <div className='flex-row flex-content-around'><span>三级告警</span><span>二级告警</span><span>一级告警</span></div>
                        <div className='flex-row flex-content-around'>
                            <div className='level3'></div>
                            <div className='level2'></div>
                            <div className='level1'></div>
                        </div>
                        {/* <div className='flex-row flex-content-around'>
                            <span>0m</span>
                            <span>5m</span>
                            <span>10m</span>
                            <span>15m</span>
                            <span>20m</span>
                            <span>25m</span>
                            <span>30m</span>
                        </div> */}
                    </div>
                </div>
            </div> :
            <div className='water_home_right_back' onClick={() => {
                setTab('overview')
                props.changeTab('overview')
            }}>
                <div className='_back_icon' /> 返回实时监测
            </div>
    }

    const renderWaterwarningbg = (alarm) => {
        return <div className='waterwarningbg'>
            <div className='_alarm_column1'>
                <div><Tooltip title={alarm.structureName}><div className='_name'>{alarm.structureName}</div></Tooltip>
                    <div className='_state'>未启动</div>
                </div>
                <div style={{ color: 'rgba(76, 161, 255, 1)', fontSize: 14 }}>[{alarm.alarms[0]?.content}]</div>
            </div>
            <div className='_alarm_column2'>
                <div style={{ textAlign: 'right', color: 'rgba(76, 161, 255, 1)' }}>{alarm.alarms[0]?.startTime}</div>
                <div className='_text_info'>
                    {alarm.alarms[0]?.details?.content}
                </div>
            </div>
        </div>
    }

    const createText = () => {
        var text = new AMap.Text({
            text: '南昌县',
            anchor: 'center', // 设置文本标记锚点
            draggable: false,
            // cursor: 'pointer',
            zooms: [3, 11],
            style: {
                'padding': '.75rem 1.25rem',
                'margin-bottom': '1rem',
                'border-radius': '.25rem',
                'background-color': 'rgba(238,77,90,0.001)',
                'width': '8rem',
                'border-width': 0,
                //'box-shadow': '0 2px 6px 0 rgba(255, 255, 255, .1)',
                'text-align': 'center',
                'font-size': '14px',
                'color': '#AFEFFF',
                'opacity': 1,
                // 'font-weight': 'bold'
            },
            position: [115.934664, 28.538966]
        });
        text.setMap(map);

    }

    const renderLayer = () => {
        if (!loca) return;
        const dataSource = trendData;

        if (gridLayer && loca) loca.remove(gridLayer)

        let data = []
        dataSource.map(x => {
            data.push({
                "type": "Feature", "properties": { "time": 1534296083, x },
                "geometry": { "coordinates": [x.lng, x.lat], "type": "Point", x }
            })
        })
        var geo = new Loca.GeoJSONSource({
            data: {
                "features": data, "type": "FeatureCollection"
            }
        });

        gridLayer = new Loca.GridLayer({
            // loca,
            zIndex: 10,
            opacity: 1,
            visible: true,
            zooms: [2, 22],
            acceptLight: true,
            // shinniness: 0,
            // cullface: 'none',
            // depth: true,
            // hasSide: true,
        });


        var colors = ['#FAE200', '#D27E37', '#C53634', '#C12B6E', '#A92E9A', '#67238A', '#211A50', '#18244E'].reverse();
        var heights = [100, 200, 400, 600, 800, 1400, 1800, 4000];
        gridLayer.setSource(geo);
        gridLayer.setStyle({
            unit: 'meter',
            radius: 400,
            gap: 10,
            altitude: 100,
            // height: function (index, feature) {
            //     return 6000

            // },
            // topColor: function (index, feature) {
            //     console.log(feature)
            //     return 'red'
            // },
            // sideColor: function (index, feature) {
            //     return 'red'
            // }
            height: function (index, feature) {
                const baseHeigh = 700
                return feature.coordinates[0].properties.x.waterLevel > 30 ? baseHeigh * 14 :
                    feature.coordinates[0].properties.x.waterLevel > 25 ? baseHeigh * 13 :
                        feature.coordinates[0].properties.x.waterLevel > 20 ? baseHeigh * 12 :
                            feature.coordinates[0].properties.x.waterLevel > 15 ? baseHeigh * 11 :
                                feature.coordinates[0].properties.x.waterLevel > 10 ? baseHeigh * 10 :
                                    feature.coordinates[0].properties.x.waterLevel > 0 ? baseHeigh * 9 : 0

            },
            topColor: function (index, feature) {
                return feature.coordinates[0].properties.x.waterLevel > Number(feature.coordinates[0].properties.x.alert) ? 'rgba(255,136,140,1)' : 'rgba(117,154,206,1)'
            },
            sideColor: function (index, feature) {
                return feature.coordinates[0].properties.x.waterLevel > Number(feature.coordinates[0].properties.x.alert) ? 'rgba(255,136,140,1)' : 'rgba(117,154,206,1)'
            },
            sideTopColor: function (index, feature) {
                return feature.coordinates[0].properties.x.waterLevel > Number(feature.coordinates[0].properties.x.alert) ? 'rgba(255,136,140,1)' : 'rgba(117,154,206,1)'
            },
            sideBottomColor: function (index, feature) {
                return feature.coordinates[0].properties.x.waterLevel > Number(feature.coordinates[0].properties.x.alert) ? 'rgba(255,136,140,0.5)' : 'rgba(117,154,206,0.5)'
            },
        });
        gridLayer = gridLayer
        loca.add(gridLayer);

        dataSource.map(s => {
            // 创建纯文本标记
            var text = new AMap.Text({
                text: '纯文本标记',
                anchor: 'center', // 设置文本标记锚点
                // draggable: true,
                cursor: 'pointer',
                angle: 0,
                // visible: false,
                offset: [0, -s.waterLevel],
                style: {
                    'padding': '2px 4px',
                    'margin-bottom': '1rem',
                    'border-radius': '.25rem',
                    'background-color': '#143857',
                    // 'width': '12rem',
                    'border-width': 0,
                    'box-shadow': '0 2px 6px 0 rgba(255, 255, 255, .3)',
                    'text-align': 'center',
                    'font-size': '14px',
                    'color': '#DCF2FD',
                },
            });
            text.setMap(map);
            text.show();
            text.setText(`${s.waterLevel || '--'}m`)
            text.setPosition(new AMap.LngLat(s.lng, s.lat));

            let infowindow = new AMap.InfoWindow({
                isCustom: true,  //使用自定义窗体
                content: `<div id="water-level" class="water-level-infowindow">
        <div style="height:${360}px;" id="contentid${s?.name}"></div></div>`,
                offset: new AMap.Pixel(100, 120)
            });


            text.on('click', () => {
                infowindow.open(map, new AMap.LngLat(s.lng, s.lat));

                setTimeout(() => {
                    if (document.getElementById(`contentid${s.name}`)) {
                        map.setCenter(new AMap.LngLat(s.lng, s.lat))
                        render(<div>
                            <div className='gis_exit'
                                style={{ right: 6, top: 67 }}
                                onClick={() => {
                                    map.setCenter([115.922069, 28.554867])
                                    map.clearInfoWindow();
                                }} />
                            <div className='gis_item'>
                                <span className='gis_title'>监测站：</span>
                                <span className='gis_text'>{s?.name}</span>
                            </div>
                            <div className='gis_item'>
                                <span className='gis_title'>实时水位：</span>
                                <span className='gis_text'>{`${s.waterLevel || '--'}m`}</span>
                            </div>
                        </div>,
                            document.getElementById(`contentid${s?.name}`));
                    }
                }, 50);

            })
        })


        // // 拾取
        // map.on('mousemove', (e) => {
        //     text.setMap(map);
        //     var feat = gridLayer.queryFeature(e.pixel.toArray());

        //     if (feat) {
        //         text.show();
        //         text.setText(feat.coordinates[0].properties.x.waterLevel + 'm');
        //         text.setPosition(e.lnglat);

        //     } else {
        //         text.hide();
        //     }
        // });
    }


    const tabs = tab == 'overview' ? [
        { name: '实时监测', tab: 'overview' },
        { name: '应急抢险', tab: 'emergency' }
    ] : [
        { name: '应急物资', tab: 'yjwz', className: 'emergency_button' },
        { name: '消防救援', tab: 'xfjy', className: 'emergency_button' },
        { name: '人民武装部', tab: 'rmwzb', className: 'emergency_button' },
        { name: '医疗救援', tab: 'yljy', className: 'emergency_button' },
        { name: '应急避难场所', tab: 'yjbns', className: 'emergency_button' },
    ]

    return (
        <>
            {/* 延缓加载遮罩 */}
            {delay && <div className='map_delay'><div className='delay_img' /></div>}


            {/* 地图容器 */}
            <div className="gis" id={MAPDOMID} />


            {/* 底部按钮 */}
            {!delay && tabs.map((s, index) => {
                return <>
                    <div className={s.className ? `${s.className} ${s.className}${index + 1}` : 'water-gis-button' + (index + 1)}
                        onClick={() => {
                            setTab(s.tab)
                            s.className ? props.changeEmengencyTab(s.tab) : props.changeTab(s.tab)
                            if (s.tab == 'emergency') {
                                setTab('yjwz')
                                props.changeEmengencyTab('yjwz')
                            }
                        }}
                    >
                        <div className={
                            s.className ? `button_img_${(index + 1)} ${tab == s.tab ? 'button_img_' + (index + 1) + '_select' : ''}` :
                                `button_img ${tab == s.tab ? 'button_img_select' : ''}`} />
                        <div>{s.name}</div>
                        {s.className && <div className='dotbg'>{emergencyList[s.tab]?.length}</div>}
                    </div>
                    {/* {
                        tab !== 'overview' && <> <div className='icon_left'></div>
                            <div className='icon_right'></div></>
                    } */}
                </>
            })
            }

            {/* 左上角图例 */}
            {tab == 'overview' && renderLeftTop()}
            {tab == 'emergency' && waterLevelAlarms.length && renderWaterwarningbg(waterLevelAlarms[0])}
            {renderRightBottom()}
            {/* 四周遮罩 */}
            <div className='gis-left'></div>
            <div className='gis-right'></div>
            <div className='gis-top'></div>
            <div className='gis-bottom'></div>
        </>
    );
}

export default connect()(Map);
